package com.centling.bluecollar.recruit.DAO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.persister.entity.Loadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import sun.java2d.opengl.OGLContext;

import com.centling.bluecollar.base.BaseHibernateDAO;
import com.centling.bluecollar.base.page.PageBean;
import com.centling.bluecollar.customer.entity.EnterpriseCustomer;
import com.centling.bluecollar.customer.entity.Organization;
import com.centling.bluecollar.privilege.entity.Account;
import com.centling.bluecollar.recruit.entity.DayRecruit;
import com.centling.bluecollar.util.StaticConstant;

/**
 * 
 * @author Administrator
 *��Ƹ����  ����ݿ� �ĵײ�ʵ������
 */
@Repository("dayRecruitDAO")
public class DayRecruitDAO extends BaseHibernateDAO{

	
	private static final Logger log = LoggerFactory
			.getLogger(DayRecruitDAO.class);			
	public void update(DayRecruit dayRecruit){
		
		log.debug("update DayRecruit instance");
		try {
			DayRecruit dayrec = (DayRecruit) this.getObjectByHQL(
					"from DayRecruit where id=? ", dayRecruit.getId());
			EnterpriseCustomer cus = (EnterpriseCustomer) this.getObjectByHQL(
					"from EnterpriseCustomer where id=?", dayRecruit.getCustomer()
							.getId());
		
		dayrec.setDate(dayRecruit.getDate());
		dayrec.setDatatime(dayRecruit.getDatatime());
		dayrec.setCustomer(cus);
		dayrec.setEntryNu(dayRecruit.getEntryNu());
		dayrec.setViewerNu(dayRecruit.getViewerNu());
		dayrec.setRemarks(dayRecruit.getRemarks());
		dayrec.setWriter(dayRecruit.getWriter());
		
		this.doSaveObject(dayrec);
		log.debug("update successful");
		
		
		}catch (RuntimeException re) {
		log.error("update failed", re);
		throw re;
	}	
}

	public void delete(String ids){
		
		log.debug("delete DayRecruit instance by id:"+ids);
		try {
			String[] id = ids.split(",");
			ArrayList arr = new ArrayList();
			StringBuffer hql = new StringBuffer(
					"delete from DayRecruit where id in (? ");
			arr.add(id[0]);
			for (int i = 1; i < id.length; i++) {
				hql.append(",?");
				arr.add(id[i]);
			}
			hql.append(")");
			this.doCUDByHQL(hql.toString(),
					this.toStringArray(arr));
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
		
	}
	public static String[] toStringArray(List<String> strList) {
		
		if (strList != null && strList.size() > 0) {
			String[] array = new String[strList.size()];
			strList.toArray(array);
			return array;
		}
		return new String[1];
	}
	public void add(DayRecruit dayRecruit){
		
		log.debug("insert into DayRecruit instance");
		try {
			EnterpriseCustomer cus = (EnterpriseCustomer) this.getObjectByHQL(
					"from EnterpriseCustomer where id=?", dayRecruit.getCustomer()
							.getId());			
			dayRecruit.setCustomer(cus);
			this.doSave(dayRecruit);
			log.debug("save successful");
			
			
		} catch (RuntimeException re) {
			
			// TODO: handle exception
		log.error("save failed",re);
		
		throw re;
		}
		
	}

	public List<DayRecruit> findById(String ids) {
		// TODO Auto-generated method stub
		log.debug("get DayRecruit instance with id"+ids);
		try {
			List<DayRecruit> list = new ArrayList();
			List arrList = new ArrayList();
			if(ids == null || ids.trim().equals(""))
			{return list;}
			
			StringBuffer hql = new StringBuffer(
					"from  DayRecruit  where id in(?");
			String[] id = ids.split(",");
			arrList.add(id[0]);
			for(int i=0;i<id.length;i++){
				hql.append(",?");
				arrList.add(id[i]);				
			}
			hql.append(")");
			list = (List<DayRecruit>) this.getListByHQL(-1, -1, hql.toString(),
				this.toStringArray(arrList));
			return list;

		} catch (RuntimeException re) {
			// TODO: handle exception
			log.debug("get failed",re);
			throw re;
		}				
	}
	@SuppressWarnings("unchecked")
	public List<DayRecruit> findByExample(PageBean page, DayRecruit instance,
			String date_start, String date_end, Account account) {
	
		 log.debug("finding DayRecruit instance by example");
		try {
			Organization organization = account.getOrganization();
			List<DayRecruit> results = new ArrayList<DayRecruit>();
			;
			List arr = new ArrayList();
			List<String> customer_id = new ArrayList<String>();
			StringBuffer sql = new StringBuffer("from DayRecruit where 1=1");
			if (instance.getOrgid() != null
					&& !instance.getOrgid().trim().equals("")) {
				customer_id = (List<String>) this.getListBySQL(-1,-1,"select id from t_enterpriseCustom where organizationId=?",instance.getOrgid());
			} else {
				// 查询默认招聘企业
				if (account.getPost().getId().equals(StaticConstant.HEADQUARTERS_BUSINESSCLERK_ID)|| account.getPost().getId().equals(StaticConstant.OPERATION_AIRPORTSTATIONED_ID)
						|| account.getPost().getId().equals(StaticConstant.BRANCH_AIRPORTSTATIONED_ID)) {
					if (account.getEnterpriseCustomers() != null){
						for (int i = 0; i < account.getEnterpriseCustomers().size(); i++)
							if (account.getEnterpriseCustomers().get(i) != null&& account.getEnterpriseCustomers().get(i).getId() != null)
								customer_id.add(account.getEnterpriseCustomers().get(i).getId());
					}else
						return results;
				} else
					customer_id = (List<String>) this.getListBySQL(-1,-1,"select id from t_enterpriseCustom where organizationId=?",organization.getId());
			}
			if (customer_id.size() > 0) {
				sql.append(" and  enterpriseCustomer_id in(?");
				arr.add(customer_id.get(0));
				for (int i = 1; i < customer_id.size(); i++) {
					sql.append(",?");
					arr.add(customer_id.get(i));
				}
				sql.append(")");
			} else
				return results;
			if (date_start != null && !date_start.trim().equals("")) {
				sql.append(" and date>=?");
				arr.add(date_start);
			}
			if (date_end != null && !date_end.trim().equals("")) {
				sql.append(" and date<=?");
				arr.add(date_end);
			}
			if (instance.getCustomer() != null
					&& instance.getCustomer().getId() != null
					&& !instance.getCustomer().getId().trim().equals("")) {
				sql.append(" and   enterpriseCustomer_id=?)");
				arr.add(instance.getCustomer().getId());
			}
			sql.append(" order by date desc");
			if (page != null)
				results = (List<DayRecruit>) this.getListByHQL(page.getPage(),
						page.getRows(), sql.toString(),
						this.toStringArray(arr));
			else {
				DayRecruit re = new DayRecruit();
				re.setWriter(""
						+ this.getCountByHQL(sql.toString(),
								this.toStringArray(arr)));
				results.add(re);
				return results;
			}
			return results;
		} catch (RuntimeException re) {
			 log.error("find by example failed", re);
			throw re;
		}
	}

	public List findqiyeAll(String org_id) {
		log.debug("finding all EnterpriseCustomer instance with id :"+org_id);
		try {
			String hql = "from EnterpriseCustomer where organizationId=? and status in(?,?)";
			return this.getListByHQL(-1, -1, hql, org_id,StaticConstant.ENTERPRISECUS_COOPERATION,StaticConstant.ENTERPRISECUS_END);
		} catch (RuntimeException re) {
			log.error("find all failed",re);
			throw re;
		}		
	}
	@Resource
	public SessionFactory sessionFactory;
	public List<DayRecruit> findByExample(int currentPage, int pageSize,Map<String, Object> searchmap,Account account) {		
		try {
			Organization organization = account.getOrganization();
			List<DayRecruit> result = new ArrayList<DayRecruit>();
			Session session = sessionFactory.getCurrentSession();					
			String hql = "from DayRecruit where 1=1 "; 
			Set<Entry<String, Object>> searchset = searchmap.entrySet();
			Iterator io = searchset.iterator();
			while (io.hasNext()) {
				Map.Entry<String, Object> me = (Map.Entry<String, Object>) io.next();
				if("date_start".equals(me.getKey()) && !"".equals(me.getValue())){
					hql += " and date >= '" + me.getValue() +"'";
				}
				if("date_end".equals(me.getKey()) && !"".equals(me.getValue())){
					hql += " and date <= '" + me.getValue() +"'";
				}
				if("customerid".equals(me.getKey()) && !"".equals(me.getValue())){
					hql += " and enterpriseCustomer_id = '" + me.getValue() +"'";
				}
				if("orgid".equals(me.getKey()) && !"".equals(me.getValue())){
					hql += " and orgid = '" + me.getValue() +"'";
				}
			}			
			Query query = session.createQuery(hql); 
			query.setFirstResult((currentPage-1)*pageSize); //从第0条开始      
			query.setMaxResults(pageSize); //取出10条           
		    List<DayRecruit> dayrecruit = query.list();	
		    return dayrecruit;

		} catch (RuntimeException re) {
			 log.error("find by example failed", re);
			throw re;
		}
	}

	public List findfenAll(Account account) {
		
		 log.debug("finding all organization by account with id:"+account.getId());
		try {
			Organization organization = account.getOrganization();
			List arr = new ArrayList();
			StringBuffer sql = new StringBuffer("from Organization ");
			//总司职员
			if (organization.getOrganizationType().getType().equals("1")){
				//公司保险部经理，运营指导
   			if (account.getPost().getId().equals(StaticConstant.HEADQUARTERS_INSURANCEMANAGER_ID)||account.getPost().getId().equals(StaticConstant.HEADQUARTERS_OPERATIONGUIDE_ID))
   				sql.append(" where organizationTypeId in('1','3' )");
			}
			else { 
				sql.append("where id=?");
				arr.add(organization.getId());
			}
			return this.getListByHQL(-1, -1, sql.toString(),
					this.toStringArray(arr));
		} catch (RuntimeException re) {
			 log.error("find all failed", re);
			throw re;
		}
	}
	
	/**
	 * 根据id获取公司对象
	 * 
	 * @param id
	 * @return
	 */
	public Organization findOrganizationById(String id) {
	
		// log.debug("find Organization instance by id:" + id);
		try {
			String hql = " from Organization as d where d.id=?";
			return (Organization) this.getObjectByHQL(hql, id);
		} catch (RuntimeException re) {
			// log.error("find by id failed", re);
			throw re;
		}
	}
	/**
	 * 根据子公司ID获取其下所有的招聘企业
	 * 
	 * @param id
	 * @return
	 */
	public List<EnterpriseCustomer> findAllEnterpriseCustomerByOrg(String id) {
	
		// log.debug("find all EnterpriseCustomer instance by Organization'id:"
		// + id);
		try {
			String hql = "from EnterpriseCustomer as e where e.organization.id=?";
			return (List<EnterpriseCustomer>) this
					.getListByHQL(-1, -1, hql, id);
		} catch (RuntimeException re) {
			// log.error("find all by Organization'id failed", re);
			throw re;
		}
	}
	}		
